package com.bigData.main.TestSocket;

import com.bigData.main.controller.FileUploadController;

import java.io.*;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class ServerThread extends Thread {
    private final Socket socket;

    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try (DataInputStream dis = new DataInputStream(socket.getInputStream());
             DataOutputStream dos = new DataOutputStream(socket.getOutputStream())) {

            // 验证对接码
            String code = dis.readUTF();
            if (!"123456".equals(code)) {
                dos.writeUTF("INVALID_CODE");
                return;
            }

            // 获取临时文件列表
            List<Path> tempFiles = FileUploadController.getTempFiles();
            dos.writeUTF("FILE_LIST");
            dos.writeInt(tempFiles.size());
            for (Path path : tempFiles) {
                dos.writeUTF(path.getFileName().toString());
                dos.writeLong(Files.size(path));
            }

            // 接收文件选择
            String selectedFile = dis.readUTF();
            Path targetFile = tempFiles.stream()
                    .filter(p -> p.getFileName().toString().equals(selectedFile))
                    .findFirst()
                    .orElse(null);

            if (targetFile == null) {
                dos.writeUTF("FILE_NOT_FOUND");
                return;
            }

            // 传输文件内容
            byte[] fileData = Files.readAllBytes(targetFile);
            dos.writeUTF("FILE_DATA");
            dos.writeInt(fileData.length);
            dos.write(fileData);

            // 处理操作指令
            String operation = dis.readUTF();
            if ("CONFIRM_UPLOAD".equals(operation)) {
                saveToFileSystem(targetFile);
                dos.writeUTF("UPLOAD_SUCCESS");
            } else {
                dos.writeUTF("OPERATION_CANCELED");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void saveToFileSystem(Path source) throws IOException {
        // 将文件保存到本地D:\hdfsxiazai目录
        File dir = new File("C:\\hdfsxiazai");
        if (!dir.exists()) {
            dir.mkdirs();
        }

        File targetFile = new File(dir, source.getFileName().toString());
        try (InputStream in = Files.newInputStream(source);
             FileOutputStream out = new FileOutputStream(targetFile)) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
    }
}